﻿using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using System;
using System.Linq;
using Volo.Abp;
using Volo.Abp.AspNetCore.ExceptionHandling;
using Volo.Abp.Authorization;
using Volo.Abp.Domain.Entities;
using Volo.Abp.ExceptionHandling.Localization;
using Volo.Abp.Http;
using Volo.Abp.Localization.ExceptionHandling;
using Volo.Abp.Validation;

namespace Xms.Abp.AspNetCore.Mvc.ExceptionHandling;

public class XmsExceptionToErrorInfoConverter : DefaultExceptionToErrorInfoConverter
{
    public XmsExceptionToErrorInfoConverter(
        IOptions<AbpExceptionLocalizationOptions> localizationOptions,
        IStringLocalizerFactory stringLocalizerFactory,
        IStringLocalizer<AbpExceptionHandlingResource> stringLocalizer,
        IServiceProvider serviceProvider)
        : base(localizationOptions, stringLocalizerFactory, stringLocalizer, serviceProvider)
    {
    }

    protected override RemoteServiceErrorInfo CreateErrorInfoWithoutCode(Exception exception, AbpExceptionHandlingOptions options)
    {
        var errorInfo = base.CreateErrorInfoWithoutCode(exception, options);
        if (options.SendExceptionsDetailsToClients)
            return errorInfo;
        errorInfo.Message = exception switch
        {
            AbpAuthorizationException => "授权失败！",
            AbpValidationException e => e.ValidationErrors.FirstOrDefault()?.ErrorMessage ?? "请求参数验证失败！",
            EntityNotFoundException => "未找到对应实体！",
            BusinessException e => e.Message,
            NotImplementedException => "该请求未实现！",
            _ => "服务器内部错误！"
        };
        return errorInfo;
    }
}
